package com.gxar.quick.ar.server.base.factory;

import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.common.enums.protocol.ArProtocolClientEnum;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.protocol.client.ClientArProtocol;
import com.gxar.quick.ar.server.base.model.protocol.client.wechat_mp.WechatMpClientArProtocol;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端协议工厂
 *
 * @author zxh
 * @version 1.0
 * @created 2024/02/23.
 */
@Component
public class ClientArProtocolFactory {

    private final Map<ArProtocolClientEnum, Class<? extends ClientArProtocol>> protocolsMap = new ConcurrentHashMap<>();

    public ClientArProtocolFactory() {
        protocolsMap.put(ArProtocolClientEnum.WECHAT_MP_CLIENT, WechatMpClientArProtocol.class);
    }

    /**
     * 创建实例
     *
     * @param clientEnum 客户端协议类型
     * @return
     */
    public ClientArProtocol create(ArProtocolClientEnum clientEnum) {
        Class<? extends ClientArProtocol> clientProtocol = protocolsMap.getOrDefault(clientEnum, null);
        if (Objects.isNull(clientProtocol)) {
            throw new APIRuntimeException(ResultCodeEnum.CONVERT_CLIENT_PROTOCOL_FAILED);
        }

        ClientArProtocol protocolInstance = null;
        try {
            protocolInstance = clientProtocol.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new APIRuntimeException(ResultCodeEnum.CONVERT_CLIENT_PROTOCOL_FAILED);
        }

        return protocolInstance;
    }
}
